package cn.xy.ymcc.service.impl;

import cn.xy.ymcc.EsMapper.HighlightResultMapper;
import cn.xy.ymcc.doc.CourseDoc;
import cn.xy.ymcc.dto.CourseSearchDto;
import cn.xy.ymcc.repository.CourseEsRepository;
import cn.xy.ymcc.result.PageList;
import cn.xy.ymcc.service.ICourseEsServise;
import cn.xy.ymcc.vo.AggrsBucket;
import cn.xy.ymcc.vo.EsAggsPageList;
import com.google.j2objc.annotations.AutoreleasePool;
import net.bytebuddy.asm.Advice;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class CourseEsServiseImpl implements ICourseEsServise {
    @Autowired
    private CourseEsRepository courseEsRepository;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;
    @Autowired
    private HighlightResultMapper highlightResultMapper;

    /**
     * 保存课程
     * @param doc
     */
    @Override
    public void saveCourse(CourseDoc doc) {
        courseEsRepository.save(doc);
    }

    /**
     * 下架课程
     * @param courseId
     */
    @Override
    public void removeCourse(Long courseId) {
        courseEsRepository.deleteById(courseId);
    }

    /**
     * 查询ES课程列表
     * @param dto
     * @return
     */
    @Override
    public PageList<CourseDoc> search(CourseSearchDto dto) {
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();

        //封装排序条件,根据前端的参数封装
        if(StringUtils.hasLength(dto.getSortField())){
            String sortField = null;
            switch (dto.getSortField().toLowerCase()){
                case "xl": sortField="saleCount";break;
                case "xp": sortField="onlineTime";break;
                case "pl": sortField="commentCount";break;
                case "jg": sortField="price";break;
                case "rq": sortField="viewCount";break;
                default: break;
            }
            //加判断
            if(sortField != null){
                //判断
                if(StringUtils.hasLength(dto.getSortType())){
                    SortOrder sortOrder = dto.getSortType().equalsIgnoreCase("ASC") ? SortOrder.ASC : SortOrder.DESC;
                    builder.withSort(new FieldSortBuilder(sortField).order(sortOrder));
                }
            }
        }

        //分页相关的参数
        builder.withPageable(PageRequest.of(dto.getPage()-1, dto.getRows()));

        //关键字查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if(StringUtils.hasLength(dto.getKeyword())){
            boolQuery.must(QueryBuilders.matchQuery("name",dto.getKeyword()));
        }

        //过滤
        if(dto.getCourseTypeId() != null){
            boolQuery.filter(QueryBuilders.termQuery("courseTypeId",dto.getCourseTypeId()));
        }
        if(StringUtils.hasLength(dto.getGradeName())){
            boolQuery.filter(QueryBuilders.termQuery("gradeName",dto.getGradeName()));
        }
        if(StringUtils.hasLength(dto.getChargeName())){
            boolQuery.filter(QueryBuilders.termQuery("chargeName",dto.getChargeName()));
        }
        if(dto.getPriceMin() != null){
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(dto.getPriceMin()));
        }
        if(dto.getPriceMax() != null){
            boolQuery.filter(QueryBuilders.rangeQuery("price").lte(dto.getPriceMax()));
        }

        // 高亮展示
        builder.withHighlightFields(
                new HighlightBuilder.Field("name")
                        .preTags("<font style='color:red'>") //设置高亮样式
                        .postTags("</font>"));


        //添加聚合查询条件
        //添加等级名字聚合
        builder.addAggregation(AggregationBuilders.terms("aggsGradeName").field("gradeName"));
        //添加收费规则聚合
        builder.addAggregation(AggregationBuilders.terms("aggsChargeName").field("chargeName"));

        builder.withQuery(boolQuery);
        NativeSearchQuery build = builder.build();
        AggregatedPage<CourseDoc> page = elasticsearchRestTemplate.queryForPage(build, CourseDoc.class, highlightResultMapper);

        //一次得到所有聚合结果，转为map
        Map<String, Aggregation> aggregationMap = page.getAggregations().asMap();

        //需要强转为ParsedStringTerms对象才会有值。
        ParsedStringTerms aggsGradeName = (ParsedStringTerms) aggregationMap.get("aggsGradeName");
        ParsedStringTerms aggsChargeName = (ParsedStringTerms)aggregationMap.get("aggsChargeName");

        //处理等级聚合结果
        List<AggrsBucket> aggrsBuckets = new ArrayList<>();
        //将得到的数组转为List< AggrsBucket >数组,需要遍历出之后一个一个转
        aggsGradeName.getBuckets().forEach(bucket -> {
            String key = bucket.getKeyAsString();
            long docCount = bucket.getDocCount();
            AggrsBucket aggrsBucket = new AggrsBucket(key, docCount);
            aggrsBuckets.add(aggrsBucket);
        });
        //处理收费规则聚合
        List< AggrsBucket> aggrsBuckets1 = new ArrayList<>();
        aggsChargeName.getBuckets().forEach(bucket -> {
            String key = bucket.getKeyAsString();
            long docCount = bucket.getDocCount();
            AggrsBucket aggrsBucket = new AggrsBucket(key, docCount);
            aggrsBuckets1.add(aggrsBucket);
        });
        Map<String, List<AggrsBucket>> map = new HashMap<>();
        map.put("aggsGradeName",aggrsBuckets);
        map.put("aggsChargeName",aggrsBuckets1);

        //封装PageList返回
        return new EsAggsPageList<>(page.getTotalElements(),page.getContent(), map);
    }

}
